<template>
  <!-- 主内容区域 -->
  <div class="content-area">
    <!-- 设置导航 -->
    <div class="settings-nav">
      <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
        <el-tab-pane label="基本设置" name="basic"></el-tab-pane>
        <el-tab-pane label="用户管理" name="users"></el-tab-pane>
        <el-tab-pane label="权限设置" name="permissions"></el-tab-pane>
        <el-tab-pane label="系统参数" name="parameters"></el-tab-pane>
        <el-tab-pane label="数据备份" name="backup"></el-tab-pane>
        <el-tab-pane label="日志查看" name="logs"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 基本设置 -->
    <div v-if="activeTab === 'basic'" class="settings-section">
      <div class="section-card">
        <div class="section-header">
          <h3>医院基本信息</h3>
        </div>
        <el-form
          :model="hospitalInfo"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="医院名称">
            <el-input
              v-model="hospitalInfo.name"
              placeholder="请输入医院名称"
            />
          </el-form-item>
          <el-form-item label="医院简称">
            <el-input
              v-model="hospitalInfo.shortName"
              placeholder="请输入医院简称"
            />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              v-model="hospitalInfo.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
          <el-form-item label="医院地址">
            <el-input
              v-model="hospitalInfo.address"
              placeholder="请输入医院地址"
            />
          </el-form-item>
          <el-form-item label="医院简介">
            <el-input
              v-model="hospitalInfo.description"
              type="textarea"
              :rows="4"
              placeholder="请输入医院简介"
            />
          </el-form-item>
          <el-form-item label="医院Logo">
            <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleLogoChange"
            >
              <el-button type="primary">选择图片</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  建议尺寸：200×200px，支持 jpg/png 格式
                </div>
              </template>
            </el-upload>
            <div v-if="hospitalInfo.logo" class="logo-preview">
              <el-image
                :src="hospitalInfo.logo"
                style="width: 100px; height: 100px; margin-top: 10px"
                fit="cover"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveHospitalInfo"
              >保存设置</el-button
            >
            <el-button @click="resetHospitalInfo">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="section-card">
        <div class="section-header">
          <h3>系统参数</h3>
        </div>
        <el-form
          :model="systemParams"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="系统名称">
            <el-input
              v-model="systemParams.systemName"
              placeholder="请输入系统名称"
            />
          </el-form-item>
          <el-form-item label="系统版本">
            <el-input v-model="systemParams.version" disabled />
          </el-form-item>
          <el-form-item label="版权信息">
            <el-input
              v-model="systemParams.copyright"
              placeholder="请输入版权信息"
            />
          </el-form-item>
          <el-form-item label="页脚信息">
            <el-input
              v-model="systemParams.footer"
              placeholder="请输入页脚信息"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveSystemParams"
              >保存设置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 用户管理 -->
    <div v-if="activeTab === 'users'" class="settings-section">
      <div class="section-header">
        <h3>用户管理</h3>
        <div>
          <el-button type="primary" @click="showAddUserDialog">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </div>

      <div class="users-table">
        <el-table :data="users" style="width: 100%" stripe>
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="realName" label="真实姓名" width="120" />
          <el-table-column prop="department" label="所属科室" width="120">
            <template #default="{ row }">
              {{ formatDepartment(row.department) }}
            </template>
          </el-table-column>
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag :type="getRoleTagType(row.role)">{{
                formatRole(row.role)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="'active'"
                :inactive-value="'inactive'"
                @change="toggleUserStatus(row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="lastLogin" label="最后登录" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons-cell">
                <el-button size="small" @click="editUser(row)">编辑</el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="resetPassword(row)"
                  >重置密码</el-button
                >
                <el-button size="small" type="danger" @click="deleteUser(row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="userPagination.currentPage"
            v-model:page-size="userPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="userPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleUserSizeChange"
            @current-change="handleUserCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 权限设置 -->
    <div v-if="activeTab === 'permissions'" class="settings-section">
      <div class="section-card">
        <div class="section-header">
          <h3>角色权限管理</h3>
        </div>

        <el-tabs type="border-card">
          <el-tab-pane
            v-for="role in roles"
            :key="role.value"
            :label="role.label"
          >
            <div class="permissions-list">
              <div
                class="permission-category"
                v-for="category in permissionCategories"
                :key="category"
              >
                <h4>{{ category }}</h4>
                <el-checkbox-group v-model="rolePermissions[role.value]">
                  <el-checkbox
                    v-for="permission in getPermissionsByCategory(category)"
                    :key="permission.value"
                    :label="permission.value"
                  >
                    {{ permission.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>

            <div class="permission-actions">
              <el-button type="primary" @click="saveRolePermissions(role.value)"
                >保存权限</el-button
              >
              <el-button @click="resetRolePermissions(role.value)"
                >重置</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 系统参数 -->
    <div v-if="activeTab === 'parameters'" class="settings-section">
      <div class="section-card">
        <div class="section-header">
          <h3>业务参数设置</h3>
        </div>

        <el-tabs type="border-card">
          <el-tab-pane label="药品管理参数">
            <el-form
              :model="medicineParams"
              label-width="200px"
              class="settings-form"
            >
              <el-form-item label="库存预警阈值">
                <el-input-number
                  v-model="medicineParams.warningThreshold"
                  :min="1"
                  :max="100"
                />
                <span class="param-desc">当库存低于此值时触发预警</span>
              </el-form-item>
              <el-form-item label="近效期预警天数">
                <el-input-number
                  v-model="medicineParams.expiryWarningDays"
                  :min="1"
                  :max="365"
                />
                <span class="param-desc">距离有效期多少天时触发预警</span>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="挂号参数">
            <el-form
              :model="registrationParams"
              label-width="200px"
              class="settings-form"
            >
              <el-form-item label="预约提前天数">
                <el-input-number
                  v-model="registrationParams.advanceDays"
                  :min="1"
                  :max="30"
                />
                <span class="param-desc">允许提前多少天预约挂号</span>
              </el-form-item>
              <el-form-item label="挂号费标准">
                <el-input-number
                  v-model="registrationParams.fee"
                  :min="0"
                  :precision="2"
                />
                <span class="param-desc">默认挂号费用（元）</span>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="系统参数">
            <el-form
              :model="systemConfigParams"
              label-width="200px"
              class="settings-form"
            >
              <el-form-item label="会话超时时间">
                <el-input-number
                  v-model="systemConfigParams.sessionTimeout"
                  :min="5"
                  :max="240"
                />
                <span class="param-desc">用户无操作自动退出时间（分钟）</span>
              </el-form-item>
              <el-form-item label="数据备份周期">
                <el-select
                  v-model="systemConfigParams.backupInterval"
                  style="width: 120px"
                >
                  <el-option label="每天" value="daily" />
                  <el-option label="每周" value="weekly" />
                  <el-option label="每月" value="monthly" />
                </el-select>
                <span class="param-desc">自动备份数据的频率</span>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div class="param-actions">
          <el-button type="primary" @click="saveAllParameters"
            >保存所有参数</el-button
          >
          <el-button @click="resetAllParameters">恢复默认值</el-button>
        </div>
      </div>
    </div>

    <!-- 数据备份 -->
    <div v-if="activeTab === 'backup'" class="settings-section">
      <div class="section-card">
        <div class="section-header">
          <h3>数据备份与恢复</h3>
        </div>

        <div class="backup-actions">
          <el-button type="primary" @click="backupData">
            <el-icon><Download /></el-icon>
            立即备份数据
          </el-button>
          <el-button type="warning" @click="showRestoreDialog">
            <el-icon><Upload /></el-icon>
            数据恢复
          </el-button>
          <el-button type="danger" @click="clearLogs">
            <el-icon><Delete /></el-icon>
            清理日志
          </el-button>
        </div>

        <div class="backup-list">
          <h4>最近备份记录</h4>
          <el-table :data="backupRecords" style="width: 100%">
            <el-table-column prop="filename" label="备份文件" width="200" />
            <el-table-column prop="size" label="文件大小" width="100">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }}
              </template>
            </el-table-column>
            <el-table-column prop="backupTime" label="备份时间" width="180" />
            <el-table-column prop="backupType" label="备份类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.backupType === 'auto' ? 'info' : 'success'">
                  {{ row.backupType === "auto" ? "自动" : "手动" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <div class="action-buttons-cell">
                  <el-button size="small" @click="downloadBackup(row)"
                    >下载</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteBackup(row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 日志查看 -->
    <div v-if="activeTab === 'logs'" class="settings-section">
      <div class="section-header">
        <h3>系统日志</h3>
        <div class="log-filters">
          <el-select
            v-model="logLevel"
            placeholder="日志级别"
            style="width: 120px"
          >
            <el-option label="全部" value="all" />
            <el-option label="信息" value="info" />
            <el-option label="警告" value="warn" />
            <el-option label="错误" value="error" />
          </el-select>
          <el-date-picker
            v-model="logDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px; margin-left: 12px"
          />
          <el-button type="primary" @click="loadLogs" style="margin-left: 12px">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
        </div>
      </div>

      <div class="logs-table">
        <el-table :data="systemLogs" style="width: 100%" stripe>
          <el-table-column prop="time" label="时间" width="160" />
          <el-table-column prop="level" label="级别" width="80">
            <template #default="{ row }">
              <el-tag :type="getLogLevelTagType(row.level)" size="small">
                {{ row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="module" label="模块" width="120" />
          <el-table-column prop="user" label="用户" width="120" />
          <el-table-column prop="action" label="操作" width="200" />
          <el-table-column
            prop="description"
            label="描述"
            show-overflow-tooltip
          />
          <el-table-column prop="ip" label="IP地址" width="120" />
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="logPagination.currentPage"
            v-model:page-size="logPagination.pageSize"
            :page-sizes="[20, 50, 100, 200]"
            :total="logPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleLogSizeChange"
            @current-change="handleLogCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>

  <!-- 新增/编辑用户对话框 -->
  <el-dialog
    v-model="userDialog.visible"
    :title="userDialog.isEdit ? '编辑用户' : '新增用户'"
    width="600px"
  >
    <el-form
      :model="userForm"
      label-width="80px"
      :rules="userRules"
      ref="userFormRef"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!userDialog.isEdit">
        <el-input
          v-model="userForm.password"
          type="password"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="userForm.role" placeholder="请选择角色">
          <el-option
            v-for="role in roles"
            :key="role.value"
            :label="role.label"
            :value="role.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室" prop="department">
        <el-select v-model="userForm.department" placeholder="请选择科室">
          <el-option
            v-for="dept in departmentOptions"
            :key="dept.value"
            :label="dept.label"
            :value="dept.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="userForm.status"
          :active-value="'active'"
          :inactive-value="'inactive'"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="userDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitUserForm">确认</el-button>
    </template>
  </el-dialog>

  <!-- 数据恢复确认对话框 -->
  <el-dialog v-model="restoreDialog.visible" title="数据恢复确认" width="500px">
    <div class="restore-warning">
      <el-alert
        title="警告"
        type="warning"
        description="数据恢复操作将覆盖当前所有数据，此操作不可逆！请谨慎操作。建议先备份当前数据。"
        show-icon
        :closable="false"
      />
    </div>
    <el-form :model="restoreForm" label-width="100px">
      <el-form-item label="选择备份文件">
        <el-select
          v-model="restoreForm.backupFile"
          placeholder="请选择备份文件"
        >
          <el-option
            v-for="file in backupRecords"
            :key="file.filename"
            :label="`${file.filename} (${formatFileSize(file.size)})`"
            :value="file.filename"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="恢复确认">
        <el-input
          v-model="restoreForm.confirmText"
          placeholder="请输入 'CONFIRM' 以确认恢复"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="restoreDialog.visible = false">取消</el-button>
      <el-button
        type="danger"
        :disabled="restoreForm.confirmText !== 'CONFIRM'"
        @click="confirmRestore"
      >
        确认恢复
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import SiderLift from "@/components/manager/SiderLift.vue";
import TopHeader from "@/components/manager/TopHeader.vue";
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const sidebarOpen = ref(false);
const router = useRouter();
const store = useStore();

const username = ref(store.state.user?.username || "管理员");
const activeTab = ref("basic");

// 医院信息
const hospitalInfo = reactive({
  name: "XX市人民医院",
  shortName: "市人民医院",
  phone: "022-88888888",
  address: "XX市西青区XX路123号",
  description: "一家集医疗、教学、科研为一体的综合性三级甲等医院",
  logo: "https://example.com/logo.png",
});

// 系统参数
const systemParams = reactive({
  systemName: "智慧医疗管理系统",
  version: "v2.1.0",
  copyright: "© 2025-2026 智医云联 | 智慧医疗大脑综合实验平台",
  footer: "技术支持：信息科 | 联系电话：022-88888888",
});

// 用户管理
const users = ref([]);
const userPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 权限设置
const roles = [
  { value: "admin", label: "系统管理员" },
  { value: "doctor", label: "医生" },
  { value: "nurse", label: "护士" },
  { value: "pharmacist", label: "药师" },
  { value: "finance", label: "财务人员" },
];

const permissionCategories = [
  "系统管理",
  "药品管理",
  "患者管理",
  "报表统计",
  "系统设置",
];
const permissions = [
  { value: "system:user:manage", label: "用户管理", category: "系统管理" },
  { value: "system:role:manage", label: "角色管理", category: "系统管理" },
  { value: "medicine:manage", label: "药品管理", category: "药品管理" },
  { value: "medicine:inventory", label: "库存管理", category: "药品管理" },
  { value: "patient:register", label: "患者挂号", category: "患者管理" },
  { value: "patient:diagnose", label: "诊断治疗", category: "患者管理" },
  { value: "report:daily", label: "日报表", category: "报表统计" },
  { value: "report:monthly", label: "月报表", category: "报表统计" },
  { value: "settings:basic", label: "基本设置", category: "系统设置" },
  { value: "settings:backup", label: "数据备份", category: "系统设置" },
];

const rolePermissions = reactive({
  admin: [
    "system:user:manage",
    "system:role:manage",
    "medicine:manage",
    "medicine:inventory",
    "patient:register",
    "patient:diagnose",
    "report:daily",
    "report:monthly",
    "settings:basic",
    "settings:backup",
  ],
  doctor: ["patient:diagnose", "report:daily"],
  nurse: ["patient:register", "patient:diagnose"],
  pharmacist: ["medicine:manage", "medicine:inventory"],
  finance: ["report:daily", "report:monthly"],
});

// 系统参数
const medicineParams = reactive({
  warningThreshold: 10,
  expiryWarningDays: 30,
});

const registrationParams = reactive({
  advanceDays: 7,
  fee: 15.0,
});

const systemConfigParams = reactive({
  sessionTimeout: 30,
  backupInterval: "daily",
});

// 数据备份
const backupRecords = ref([]);

// 日志查看
const systemLogs = ref([]);
const logLevel = ref("all");
const logDateRange = ref([]);
const logPagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

// 用户对话框
const userDialog = reactive({
  visible: false,
  isEdit: false,
});

const userForm = reactive({
  username: "",
  realName: "",
  password: "",
  role: "doctor",
  department: "",
  email: "",
  phone: "",
  status: "active",
});

const userRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
};

const userFormRef = ref(null);

// 数据恢复对话框
const restoreDialog = reactive({
  visible: false,
});

const restoreForm = reactive({
  backupFile: "",
  confirmText: "",
});

// 科室选项
const departmentOptions = [
  { value: "D001", label: "内科" },
  { value: "D002", label: "外科" },
  { value: "D003", label: "儿科" },
  { value: "D004", label: "妇产科" },
  { value: "D005", label: "眼科" },
  { value: "D006", label: "耳鼻喉科" },
  { value: "D007", label: "口腔科" },
  { value: "D008", label: "皮肤科" },
  { value: "D009", label: "急诊科" },
  { value: "D010", label: "检验科" },
  { value: "D011", label: "影像科" },
];

// 初始化数据
onMounted(() => {
  loadUsers();
  loadBackupRecords();
  loadLogs();
});

// 加载用户数据
const loadUsers = () => {
  // 模拟用户数据
  users.value = [
    {
      id: 1,
      username: "admin",
      realName: "系统管理员",
      department: "D011",
      role: "admin",
      email: "admin@hospital.com",
      phone: "13800138000",
      status: "active",
      lastLogin: "2024-01-15 09:30:25",
    },
    {
      id: 2,
      username: "doctorzhang",
      realName: "张医生",
      department: "D001",
      role: "doctor",
      email: "zhang@hospital.com",
      phone: "13900139000",
      status: "active",
      lastLogin: "2024-01-15 08:15:10",
    },
    {
      id: 3,
      username: "nurseli",
      realName: "李护士",
      department: "D009",
      role: "nurse",
      email: "li@hospital.com",
      phone: "13700137000",
      status: "active",
      lastLogin: "2024-01-14 16:45:30",
    },
  ];
  userPagination.total = users.value.length;
};

// 加载备份记录
const loadBackupRecords = () => {
  backupRecords.value = [
    {
      filename: "backup_20240115.sql",
      size: 1024000,
      backupTime: "2024-01-15 02:00:00",
      backupType: "auto",
    },
    {
      filename: "backup_20240114.sql",
      size: 1023000,
      backupTime: "2024-01-14 02:00:00",
      backupType: "auto",
    },
    {
      filename: "manual_backup_20240113.sql",
      size: 1022000,
      backupTime: "2024-01-13 15:30:00",
      backupType: "manual",
    },
  ];
};

// 加载日志
const loadLogs = () => {
  // 模拟日志数据
  systemLogs.value = [
    {
      time: "2024-01-15 09:30:25",
      level: "INFO",
      module: "用户登录",
      user: "admin",
      action: "登录系统",
      description: "用户admin成功登录系统",
      ip: "192.168.1.100",
    },
    {
      time: "2024-01-15 08:15:10",
      level: "INFO",
      module: "药品管理",
      user: "doctorzhang",
      action: "药品查询",
      description: "查询了抗生素类药品",
      ip: "192.168.1.101",
    },
    {
      time: "2024-01-14 16:45:30",
      level: "WARN",
      module: "系统备份",
      user: "admin",
      action: "数据备份",
      description: "自动备份完成，耗时2分30秒",
      ip: "192.168.1.100",
    },
  ];
  logPagination.total = systemLogs.value.length;
};

// 切换标签页
const handleTabChange = (tabName) => {
  activeTab.value = tabName;
};

// 保存医院信息
const saveHospitalInfo = () => {
  ElMessage.success("医院信息保存成功");
};

// 重置医院信息
const resetHospitalInfo = () => {
  ElMessage.info("已重置医院信息");
};

// 保存系统参数
const saveSystemParams = () => {
  ElMessage.success("系统参数保存成功");
};

// 显示新增用户对话框
const showAddUserDialog = () => {
  Object.assign(userForm, {
    username: "",
    realName: "",
    password: "",
    role: "doctor",
    department: "",
    email: "",
    phone: "",
    status: "active",
  });
  userDialog.isEdit = false;
  userDialog.visible = true;
};

// 编辑用户
const editUser = (user) => {
  Object.assign(userForm, user);
  userDialog.isEdit = true;
  userDialog.visible = true;
};

// 提交用户表单
const submitUserForm = async () => {
  try {
    await userFormRef.value.validate();

    if (userDialog.isEdit) {
      ElMessage.success("用户信息更新成功");
    } else {
      ElMessage.success("用户添加成功");
    }

    userDialog.visible = false;
    loadUsers();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 重置密码
const resetPassword = (user) => {
  ElMessageBox.confirm(
    `确定要重置用户 ${user.realName} 的密码吗？`,
    "重置密码确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      ElMessage.success("密码已重置为默认密码");
    })
    .catch(() => {
      ElMessage.info("已取消重置");
    });
};

// 删除用户
const deleteUser = (user) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${user.realName} 吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      users.value = users.value.filter((u) => u.id !== user.id);
      ElMessage.success("用户删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 切换用户状态
const toggleUserStatus = (user) => {
  const action = user.status === "active" ? "启用" : "停用";
  ElMessage.success(`用户${action}成功`);
};

// 获取权限按分类
const getPermissionsByCategory = (category) => {
  return permissions.filter((p) => p.category === category);
};

// 保存角色权限
const saveRolePermissions = (role) => {
  ElMessage.success(`${formatRole(role)}权限保存成功`);
};

// 重置角色权限
const resetRolePermissions = (role) => {
  ElMessage.info(`${formatRole(role)}权限已重置`);
};

// 保存所有参数
const saveAllParameters = () => {
  ElMessage.success("所有参数保存成功");
};

// 重置所有参数
const resetAllParameters = () => {
  ElMessage.info("所有参数已恢复默认值");
};

// 备份数据
const backupData = () => {
  ElMessage.success("数据备份成功");
};

// 显示恢复对话框
const showRestoreDialog = () => {
  restoreForm.backupFile = "";
  restoreForm.confirmText = "";
  restoreDialog.visible = true;
};

// 确认恢复
const confirmRestore = () => {
  ElMessageBox.confirm(
    "确定要恢复数据吗？此操作将覆盖所有现有数据！",
    "最终确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "error",
    }
  )
    .then(() => {
      ElMessage.success("数据恢复成功");
      restoreDialog.visible = false;
    })
    .catch(() => {
      ElMessage.info("已取消恢复");
    });
};

// 清理日志
const clearLogs = () => {
  ElMessageBox.confirm(
    "确定要清理所有日志吗？此操作不可恢复！",
    "清理日志确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      systemLogs.value = [];
      ElMessage.success("日志清理成功");
    })
    .catch(() => {
      ElMessage.info("已取消清理");
    });
};

// 下载备份
const downloadBackup = (backup) => {
  ElMessage.success(`开始下载: ${backup.filename}`);
};

// 删除备份
const deleteBackup = (backup) => {
  ElMessageBox.confirm(
    `确定要删除备份文件 ${backup.filename} 吗？`,
    "删除备份确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      backupRecords.value = backupRecords.value.filter(
        (b) => b.filename !== backup.filename
      );
      ElMessage.success("备份文件删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 格式化科室
const formatDepartment = (deptCode) => {
  const dept = departmentOptions.find((d) => d.value === deptCode);
  return dept ? dept.label : deptCode;
};

// 格式化角色
const formatRole = (role) => {
  const roleObj = roles.find((r) => r.value === role);
  return roleObj ? roleObj.label : role;
};

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    admin: "danger",
    doctor: "success",
    nurse: "primary",
    pharmacist: "warning",
    finance: "info",
  };
  return types[role] || "default";
};

// 获取日志级别标签类型
const getLogLevelTagType = (level) => {
  const types = {
    INFO: "success",
    WARN: "warning",
    ERROR: "danger",
  };
  return types[level] || "info";
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + " B";
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
  return (bytes / (1024 * 1024)).toFixed(1) + " MB";
};

// 处理Logo上传
const handleLogoChange = (file) => {
  hospitalInfo.logo = "https://example.com/new-logo.png";
  ElMessage.success("Logo上传成功");
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "退出确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.push("/login");
      ElMessage.success("已退出登录");
    })
    .catch(() => {
      ElMessage.info("已取消退出");
    });
};

// 切换侧边栏
const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

// 分页处理
const handleUserSizeChange = (size) => {
  userPagination.pageSize = size;
  loadUsers();
};

const handleUserCurrentChange = (page) => {
  userPagination.currentPage = page;
  loadUsers();
};

const handleLogSizeChange = (size) => {
  logPagination.pageSize = size;
  loadLogs();
};

const handleLogCurrentChange = (page) => {
  logPagination.currentPage = page;
  loadLogs();
};
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0;  // 添加这行
  min-height: 100%;  // 添加这行
  overflow-y: auto;  // 确保有这行
}

.settings-nav {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 24px;
  padding: 0 20px;
}

.settings-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-card {
  margin-bottom: 24px;
}

.section-card:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.settings-form {
  max-width: 600px;
}

.logo-preview {
  margin-top: 10px;
}

.param-desc {
  margin-left: 12px;
  font-size: 12px;
  color: #909399;
}

.param-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}

.users-table,
.logs-table {
  margin-top: 20px;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.permissions-list {
  max-height: 400px;
  overflow-y: auto;
}

.permission-category {
  margin-bottom: 20px;
}

.permission-category h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-weight: 500;
}

.permission-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}

.backup-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.backup-list {
  margin-top: 20px;
}

.backup-list h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-weight: 500;
}

.log-filters {
  display: flex;
  align-items: center;
}

.restore-warning {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .settings-nav :deep(.el-tabs__nav-wrap) {
    overflow-x: auto;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .log-filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .backup-actions {
    flex-direction: column;
  }

  .action-buttons-cell {
    flex-direction: column;
  }
}
</style>